@namespace Oqtane.Themes.Controls
@using System.Net
@inherits ThemeControlBase
@inject ISettingService SettingService
@inject IStringLocalizer<Search> Localizer
@inject NavigationManager NavigationManager

@if (_searchResultsPage != null)
{
    <span class="@_defaultCssClass @CssClass">
        <form method="post" class="app-form-inline" @formname="@($"SearchForm")" @onsubmit="@PerformSearch" data-enhance>
            <input type="hidden" name="@Constants.RequestVerificationToken" value="@SiteState.AntiForgeryToken" />
            @if (AllowTextInput)
            {
                <input type="text" name="keywords" maxlength="50"
                        class="form-control d-inline-block pe-5 shadow-none"
                        @bind="_keywords"
                        placeholder="@Localizer["SearchPlaceHolder"]"
                        aria-label="Search" />
            }
            <button type="submit" class="btn btn-search" aria-label="Search Button">
                <span class="oi oi-magnifying-glass align-middle"></span>
            </button>
        </form>
    </span>
}

@code {
    private string _defaultCssClass;
    private Page _searchResultsPage;
    private string _keywords = "";

    [Parameter]
    public string CssClass { get; set; }

    [Parameter]
    public bool AllowTextInput { get; set; } = true; // setting to false will display only the search icon button - not the textbox

    [Parameter]
    public string SearchResultPagePath { get; set; } = "search"; // setting to "" will disable search

    [SupplyParameterFromForm(FormName = "SearchForm")]
    public string KeyWords { get => ""; set => _keywords = value; }

    protected override void OnInitialized()
    {
        if (bool.Parse(SettingService.GetSetting(PageState.Site.Settings, "Search_Enabled", "True")))
        {
            _defaultCssClass = (AllowTextInput) ? "app-search" : "app-search-noinput";
            if (!string.IsNullOrEmpty(SearchResultPagePath))
            {
                _searchResultsPage = PageState.Pages.FirstOrDefault(i => i.Path == SearchResultPagePath);
            }
        }
    }

    private void PerformSearch()
    {
        if (_searchResultsPage != null)
        {
            var url = NavigateUrl(_searchResultsPage.Path, $"q={WebUtility.UrlEncode(_keywords)}");
            NavigationManager.NavigateTo(url);
        }
    }
}


